#!/bin/bash
set -u -e -E -C -o pipefail

BUILD_HOST=${1?:BUILD_HOST not given}

if [[ -d target/dist ]]; then
    LATEST=$(ls -1 target/dist/ | sort | tail -n 1)
    DIST_DIR=target/dist/$LATEST/dist
    VERSION=$LATEST
elif [[ -d dist ]]; then 
    DIST_DIR=dist
    VERSION=$(basename $(ls -1 $DIST_DIR/*.tar.gz | sort | tail -n 1) .tar.gz)
else
    echo "no dist dir found, aborting"
    exit 1
fi

ARTEFACT=$VERSION.tar.gz
echo "building rpm from $DIST_DIR/$ARTEFACT on $BUILD_HOST"

scp $DIST_DIR/$ARTEFACT $BUILD_HOST:
ssh $BUILD_HOST "
    mkdir -p ~/build ~/dist 
    mv $ARTEFACT build

    cd build
    tar zxvf $ARTEFACT
    cd $VERSION

    python setup.py bdist_rpm
    cp -v dist/*.rpm ~/dist
"

mkdir -p dist-rpms
scp $BUILD_HOST:build/$VERSION/dist/*.rpm dist-rpms

